<template>
  <div id="app">
    <van-nav-bar title="工单详情" left-text="返回" left-arrow @click-left="onClickLeft">
      <template #right>
        <div :hidden="!finishWx">
          <van-icon name="scan" size="28" @click="searchEq()" />
        </div>
      </template>
    </van-nav-bar>
    <van-tabs v-model:active="active">
      <van-tab title="详情">
        <div class="order-detail">
          <van-form @submit="submitReading">
            <van-collapse v-model="activeName" accordion v-for="(item, eqIndex) in eqList" :key="eqIndex">
              <van-collapse-item :title="item[0].eq" :name="eqIndex+1" :disabled="!disSend">
                <div v-for="(trueItem, trueIndex) in item" :key="trueIndex" class="innerBox">
                  <div style="overflow: hidden">
                    <span class="fl font-black">{{ trueItem.v.task.name }}</span>
                    <span class="fr font-black">
                      <span class="font-black mr10">{{ trueItem.v.param.name }} </span>
                      <van-icon name="photo" size="14" @click="takePhoto(trueItem.v.id, trueIndex, trueItem.v.eq.id)" />
                    </span>
                  </div>
                  <div style="overflow: hidden" v-if="trueItem.v.task.detail">
                    <span class="font-black">任务细节：</span> <span class="font-black">{{ trueItem.v.task.detail }}</span>
                  </div>
                  <div style="overflow: hidden" v-if="trueItem.v.param.standard">
                    <span class="font-black">参数标准：</span> <span class="font-black">{{ trueItem.v.param.standard }}</span>
                  </div>
                  <div v-if="trueItem.v.param.category === 3">
                    <van-radio-group v-model="trueItem.v.reading" direction="horizontal" style="margin: 1px 0 6px;">
                      <van-radio name="1">正常</van-radio>
                      <van-radio name="2">不正常</van-radio>
                    </van-radio-group>
                  </div>
                  <div v-else>
                    <van-field v-model="trueItem.v.reading" label="读数" placeholder="请输入读数" name="reading" class="innerReading" />
                  </div>
                  <img :src="host+trueItem.v.photo" alt="" v-if="trueItem.v.photo" width="100" height="100">
                </div>
              </van-collapse-item>
            </van-collapse>
            <div v-if="data.status === 0" style="margin: 16px;">
              <van-button round block type="primary" native-type="submit">提交</van-button>
              <van-button round block color="#0cc15f" native-type="button" @click="finishHandle" style="margin-top: 10px;">完成</van-button>
            </div>
          </van-form>
        </div>
      </van-tab>
      <van-tab title="备件">
        <van-pull-refresh v-model="detailLoading" @refresh="onDetailRefresh">
          <div class="order-detail">
            <van-cell-group>
              <van-cell title="备件名称" value="数量单位" label="型号" title-class="tl" />
              <van-swipe-cell v-for="item in parts.data" :key="item">
                <van-cell v-if="item.already === 2">
                  <div class="fl" style="color: green">{{ item.parts.name }}-{{ item.parts.spec }}</div>
                  <div class="fr" style="color: green">{{ item.number }}</div>
                </van-cell>
                <van-cell v-else-if="item.already === 1">
                  <div class="fl" style="color: blue">{{ item.parts.name }}-{{ item.parts.coding }}</div>
                  <div class="fr" style="color: blue">{{ item.number }}</div>
                </van-cell>
                <van-cell v-else>
                  <div class="fl">{{ item.parts.name }}-{{ item.parts.coding }}</div>
                  <div class="fr">{{ item.number }}</div>
                </van-cell>
                <template #right>
                  <van-button square type="danger" text="删除" @click="removePartsHandle(item.id, item.already)" />
                </template>
              </van-swipe-cell>
            </van-cell-group>
            <div v-if="parts.data.length > 0 && data.status === 0" style="margin: 16px;">
              <van-button round block type="primary" @click="getParts">请求</van-button>
            </div>
            <div v-if="data.status === -1 || data.status === 0">
              <div class="cell">
                <van-field v-model="partsPicker" label="备件" placeholder="请选择备件" @click="showPartsPicker = true" />
              </div>
              <van-popup v-model:show="showPartsPicker" position="bottom">
                <van-picker show-toolbar :columns="partsList" @confirm="onPartsConfirm" @cancel="showPartsPicker = false" value-key="name" :loading="loadingPartsPicker">
                  <template #title>
                    <van-search v-model="partsQuery.name" @search="searchPartsPicker" placeholder="请输入搜索关键词" />
                  </template>
                </van-picker>
              </van-popup>
              <p class="fz-16">
                <span>当前数量：{{ partsNumber }}</span>
              </p>
              <van-field v-model="needPartsNumber" type="digit" label="需要数量" />
              <div class="buttonBox mt-10">
                <van-button round block color="#1890ff" @click="appendPartsHandle">添加备件</van-button>
              </div>
            </div>
          </div>
        </van-pull-refresh>
      </van-tab>
      <van-tab title="员工">
        <div class="order-detail">
          <van-pull-refresh v-model="detailLoading" @refresh="onDetailRefresh">
            <van-cell v-for="item in data.other_member" :key="item">
              <van-swipe-cell>
                <van-cell :border="false" :title="item.admin.name" />
                <template v-if="[-1 ,0].includes(data.status)" #right>
                  <van-button square type="danger" @click="removeAdmin(item.id)" text="删除" />
                </template>
              </van-swipe-cell>
            </van-cell>
          </van-pull-refresh>
          <div v-if="[-1, 0].includes(data.status) && data.admin_id === userId || userId === 1" style="margin-top: 10px;">
            <div class="cell">
              <van-field v-model="adminPicker" label="员工" placeholder="请选择员工" @click="showAdminPicker = true" />
            </div>
            <van-popup v-model:show="showAdminPicker" position="bottom">
              <van-picker show-toolbar :columns="adminList" @confirm="onConfirm" @cancel="showAdminPicker = false" value-key="name" :loading="loadingPicker">
                <template #title>
                  <van-search v-model="adminQuery.name" @search="searchPicker" placeholder="请输入搜索关键词" />
                </template>
              </van-picker>
            </van-popup>
            <div class="buttonBox" style="margin-top: 16px;">
              <van-button round block color="#1890ff" @click="appendAdminHandle">添加人员</van-button>
            </div>
          </div>
        </div>
      </van-tab>
      <van-tab title="工单">
        <van-pull-refresh v-model="detailLoading" @refresh="onDetailRefresh">
          <van-loading color="#1989fa" class="page-loading" :hidden="pmLoadingHidden" />
          <div class="order-detail" :hidden="pmLoading">
            <van-field v-model="data.coding" label="编号" readonly />
            <van-field v-model="data.name" label="名称" readonly />
            <van-field v-model="data.admin.name" label="负责人" readonly />
            <van-field v-model="data.admin.phone" label="电话" readonly />
            <van-field v-model="data.arrange_date" label="安排时间" readonly />
            <van-field v-if="data.plan" v-model="data.plan.period" label="计划周期" readonly />
            <van-field v-if="isOnce || giveOut || isAdmin" v-model="data.bz_check_show" label="班长审核" readonly />
            <van-field v-if="isOnce || giveOut || isAdmin" v-model="data.engineer_check_show" label="工程师审核" readonly />
            <van-field v-if="!isOnce && !giveOut" v-model="data.planName" label="维护计划" />
            <van-field v-if="data.complete_date" v-model="data.complete_date" label="完成时间" />
            <van-field v-if="data.wxBz" v-model="data.bz_admin.name" label="班长" />
            <van-field v-if="data.wxBz_date" v-model="data.wxBz_date" label="班长确认时间" />
            <van-field v-if="data.engineer" v-model="data.engineer_admin.name" label="工程师" />
            <van-field v-if="data.engineer_date" v-model="data.engineer_date" label="工程师确认时间" />
            <div style="margin: 16px;">
              <div v-if="canBz" class="buttonBox">
                <van-button round block type="danger" @click="bzBackHandle" class="mb20">班长退回</van-button>
                <van-button round block type="success" @click="bzHandle" class="mt-10">班长确认</van-button>
              </div>
              <div v-if="canEngineer" class="buttonBox">
                <van-button round block type="danger" @click="engineerBackHandle" class="mb20">工程师退回</van-button>
                <van-button round block type="success" @click="engineerHandle" class="mt-10">工程师确认</van-button>
              </div>
              <div v-if="data.status === -1 && data.admin_id === userId" class="buttonBox">
                <van-button round block color="#07c160" @click="handOut">派发</van-button>
              </div>
              <div v-if="isOnce || !zy" class="buttonBox" hidden>
                <van-button round block color="#07c160" @click="save">提交</van-button>
              </div>
            </div>
          </div>
        </van-pull-refresh>
      </van-tab>
      <van-tab title="延期">
        <van-collapse v-model="delayName" v-for="(item, delayIndex) in delayList" :key="delayIndex" accordion>
          <van-collapse-item :title="`${item.day}天`" :name="delayIndex+1" style="text-align: left">
            <p>状态：
              <span v-if="item.status === 0">待班长审核</span>
              <span v-if="item.status === 1">待工程师审核</span>
              <span v-if="item.status === 2">待科长审核</span>
              <span v-if="item.status === 3">完成</span>
            </p>
            <p>原因：{{ item.reason }}</p>
            <p>申请时间：{{ item.create_time }}</p>
            <div style="margin: 16px;">
              <div v-if="item.status === 0" class="buttonBox">
                <van-button round block type="success" class="mt-10" @click="reviewDelay(item.id, 1)">班长审批</van-button>
              </div>
              <div v-if="item.status === 1" class="buttonBox">
                <van-button round block type="success" class="mt-10" @click="reviewDelay(item.id, 2)">工程师审批</van-button>
              </div>
              <div v-if="item.status === 2" class="buttonBox">
                <van-button round block type="success" class="mt-10" @click="reviewDelay(item.id, 3)">科长审批</van-button>
              </div>
            </div>
          </van-collapse-item>
        </van-collapse>
        <div v-if="data.status === -1"><van-form @submit="appendDelay">
          <van-field v-model="delayData.day" type="digit" label="天数" />
          <van-field v-model="delayData.reason" rows="1" :autosize="true" label="原因" type="textarea" placeholder="请填写原因" />
          <div style="margin: 16px;">
            <van-button round block type="primary" native-type="submit">提交</van-button>
          </div>
        </van-form></div>
        <div v-else>
          <span style="font-size: 16px;">该状态只能联系管理员延期。</span>
        </div>
      </van-tab>
    </van-tabs>
  </div>
</template>

<script>
import API from '@/api/maintain/pm3'
import SELECT from '@/api/select'
import { groupType, profession, planType, planSend } from '@/utils/options'
import {Dialog, Notify, Toast} from 'vant'
import WxApi from "@/api/wx"
import wx from "weixin-js-sdk"
import { mapGetters } from "vuex"
export default {
  inject: ['backUrl', 'reload', 'showSize', 'goUrl', 'getScope'],
  data() {
    return{
      data: {
        admin: {
          name: null,
          phone: null
        },
        eqShow: null
      },
      delayData: {},
      eqList: [],
      parts: {
        data: []
      },
      delayList: [],
      host: 'https:router.ubeiyun.com/',
      activeName: '1',
      active: 0,
      delayName: 0,
      detailLoading: false,
      pmLoadingHidden: false,
      pmLoading: true,
      groupType,
      profession,
      planType,
      planSend,
      isOnce: false,
      zy: true,
      giveOut: false,
      isAdmin: true,
      canBz: false,
      canParts: false,
      canEngineer: false,
      loadingPicker: false,
      adminPicker: '',
      adminId: '',
      showAdminPicker: false,
      adminQuery: {
        name: '',
        limit: 100
      },
      adminList: [],
      loadingPartsPicker: false,
      partsPicker: '',
      partsId: '',
      showPartsPicker: false,
      partsList: [],
      partsQuery: {
        name: '',
        add_field: 'coding',
        limit: 100
      },
      needPartsNumber: null,
      partsNumber: '--',
      disSend: true,
      canTakePhoto: false,
      finishWx: false,
      monitor: false,
      scope: null,
      thisEngineer: [],
      engineerList: []
    }
  },
  computed: {
    ...mapGetters(['userId'])
  },
  created() {
    this.getConfig()
    this.index()
    if (this.$route.query.eqId) {
      this.activeName = this.$route.query.eqId + '1'
    }

    if (this.$route.query.bzCheck === '1') {
      sessionStorage.setItem('pm3Bz', '1')
      this.active = 3
    }

    if (this.$route.query.engineerCheck === '1') {
      sessionStorage.setItem('pm3Engineer', '1')
      this.active = 3
    }
  },
  methods: {
    index() {
      this.scope = this.getScope(this.userId)
      // 1 管理员 2 班长 3 工程师 4 推进员
      if ([1, 2, 3, 4].includes(this.scope)) {
        this.monitor = true
      }

      const that = this
      this.pmLoadingHidden = false
      this.pmLoading = true
      const id = this.$route.params.id
      API.getOne(id).then(response => {
        if (response.data.error_code) {
          Dialog.alert({
            title: '错误',
            message: '您请求的工单不存在'
          }).then(() => {
            this.backUrl()
          })
        }
        if (response.data.status === -1) {
          this.active = 3
        }
        this.data = response.data
        this.data.profession = profession[this.data.profession]
        this.data.typeShow = groupType[this.data.type]
        this.data.unitShow = planType[this.data.unit]
        const eqData = {
          type: response.data.type,
          unit: response.data.unit,
          id: response.data.equipment_id
        }
        SELECT.eqList(eqData).then(eqRes => {
          const eq = eqRes.data.data[0]
          that.data.eqShow = eq.name
        })
        if (response.data.plan_id) {
          API.plan(response.data.plan_id).then(planRes => {
            that.data.planName = planRes.data.name
          })
        } else {
          that.data.planName = null
        }
        this.adminQuery.monitor = this.userId
        SELECT.adminList(this.adminQuery).then(res => {
          console.log(res)
          this.adminList = res.data.data
        })
        this.engineerList = response.data.other_engineer
        if (this.engineerList.length > 0) {
          this.engineerList.map((i) => {
            this.thisEngineer.push(i.admin_id)
          })
        }
        // console.log(this.partsQuery)
        // SELECT.partsList(this.partsQuery).then(partsRes => {
        //   this.partsList = partsRes.data.data
        // })

        this.data.bz_check_show = planSend[this.data.bz_check]
        this.data.engineer_check_show = planSend[this.data.engineer_check]

        this.parts.data = response.data.other_parts
        this.eqList = response.data.asame_eq

        if ([-1 ,0].includes(response.data.status)) {
          this.disSend = false
        } else {
          this.disSend = true
        }

        if (response.data.status === 0) {
          this.canTakePhoto = true
        }

        if (!response.data.plan_id) {
          this.isOnce = true
        }
        if (response.data.plan_id === -1) {
          this.giveOut = true
        }
        // 仅班长确认
        if (response.data.bz_check === 1 && response.data.engineer_check === 0) {
          if (response.data.status === 1 && this.scope === 2) {
            this.canBz = true
          }
        }
        // 仅工程师确认
        if (response.data.bz_check === 0 && response.data.engineer_check === 1) {
          if (response.data.status === 1 && this.thisEngineer.includes(this.userId)) {
            this.canEngineer = true
          }
        }
        // 班长和工程师都需要确认
        if (response.data.bz_check === 1 && response.data.engineer_check === 1) {
          if (response.data.status === 1 && this.scope === 2) {
            this.canBz = true
          } else if (response.data.status === 2 && this.thisEngineer.includes(this.userId)) {
            this.canEngineer = true
          }
        }
        if (response.data.plan_category === 2 || !response.data.plan_id) {
          this.zy = false
        }

        this.delayList = response.data.delays
      }).finally(() => {
        this.pmLoadingHidden = true
        this.pmLoading = false
        this.detailLoading = false
      })
    },
    onClickLeft() {
      this.$router.go(-1)
    },
    onDetailRefresh() {
      this.detailLoading = true
      this.showToast = true
      this.index()
    },
    getParts() {
      const needData = {
        id: this.data.id
      }
      API.needParts(needData).then(response => {
        if (response.data.error_code === 1) {
          Notify({
            type: 'success',
            message: '请求备件，请速去库房领件！'
          })
          this.backUrl()
        } else {
          Notify({
            type: 'danger',
            message: response.data.message
          })
        }
      })
    },
    submitReading() {
      let sub = Object.assign({},this.eqList)
      sub.submitType = 'm'
      sub.autoFinish = 'm'
      sub.cm_category = 4
      API.submitReading(sub).then((response) => {
        if (response.data.error_code === 1) {
          Notify({
            type: 'success',
            message: '恭喜你，提交成功'
          })
          this.index()
          this.activeName = null
        } else if (response.data.error_code === 11) {
          Notify({
            type: 'success',
            message: '参数不正常，已自动生成报修单'
          })
          this.index()
          this.activeName = null
        } else {
          Notify({
            type: 'danger',
            message: response.data.message
          })
        }
      })
    },
    finishHandle() {
      const reviewData = {
        'status': 1,
        'id': this.$route.params.id
      }
      API.review(reviewData).then((response) => {
        if (response.data.error_code === 1) {
          Notify({
            type: 'success',
            message: '恭喜你，提交成功'
          })
          this.goUrl('/order/pm3')
        } else {
          Notify({
            type: 'danger',
            message: response.data.message
          })
        }
      })
    },
    bzHandle() {
      const reviewData = {
        'status': 2,
        'content': this.data.content,
        'id': this.$route.params.id
      }
      API.review(reviewData).then((response) => {
        if (response.data.error_code === 1) {
          Notify({
            type: 'success',
            message: '恭喜你，提交成功'
          })
          this.goUrl('/order/pm3')
        } else {
          Notify({
            type: 'danger',
            message: response.data.message
          })
        }
      })
    },
    bzBackHandle() {
      const reviewData = {
        'status': 21,
        'content': this.data.content,
        'id': this.$route.params.id
      }
      API.review(reviewData).then((response) => {
        if (response.data.error_code === 1) {
          Notify({
            type: 'success',
            message: '恭喜你，提交成功'
          })
          this.goUrl('/order/pm3')
        } else {
          Notify({
            type: 'danger',
            message: response.data.message
          })
        }
      })
    },
    engineerHandle() {
      const reviewData = {
        'status': 3,
        'content': this.data.content,
        'id': this.$route.params.id
      }
      API.review(reviewData).then((response) => {
        if (response.data.error_code === 1) {
          Notify({
            type: 'success',
            message: '恭喜你，提交成功'
          })
          this.goUrl('/order/pm3')
        } else {
          Notify({
            type: 'danger',
            message: response.data.message
          })
        }
      })
    },
    engineerBackHandle() {
      const reviewData = {
        'status': 22,
        'content': this.data.content,
        'id': this.$route.params.id
      }
      API.review(reviewData).then((response) => {
        if (response.data.error_code === 1) {
          Notify({
            type: 'success',
            message: '恭喜你，提交成功'
          })
          this.goUrl('/order/pm3')
        } else {
          Notify({
            type: 'danger',
            message: response.data.message
          })
        }
      })
    },
    save() {},
    getConfig() {
      const self = this
      let url = /(Android)/i.test(navigator.userAgent) ? location.href.split('#')[0] : window.localStorage.getItem('scanUrl');

      WxApi.wxJSTicket({ url: url }).then((res) => {
        const data = res.data;
        wx.config({
          beta: true,
          debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
          appId: data.appId, // 必填，公众号的唯一标识
          timestamp: data.timestamp, // 必填，生成签名的时间戳
          nonceStr: data.nonceStr, // 必填，生成签名的随机串
          signature: data.signature, // 必填，签名
          jsApiList: ['chooseImage','uploadImage','getLocalImgData','scanQRCode','checkJsApi'] // 必填，需要使用的JS接口列表
        })
        wx.ready(function () {
          console.log("成功")
          self.finishWx = true
        })
        wx.error(function (err) {
          console.log(err)
        })
      })
    },
    checkJsApi(api) {
      //检测api是否可用
      return new Promise((rel, err) => {
        wx.checkJsApi({
          jsApiList: [api], // 需要检测的JS接口列表，所有JS接口列表见附录2,
          success: function (res) {
            // 以键值对的形式返回，可用的api值true，不可用为false
            // 如：{"checkResult":{"chooseImage":true},"errMsg":"checkJsApi:ok"}
            if (res.checkResult && res.checkResult.chooseImage == false) {
              this.$toast("微信版本较低，请升级后重试！")
              err("版本低")
            } else {
              rel(true)
            }
          }
        })
      })
    },
    takePhoto(id, index, eqId) {
      console.log(id, index, eqId)
      const self = this
      this.checkJsApi("scanQRCode").then((rel) => {
        if (rel) {
          wx.chooseImage({
            count: 1, // 默认9
            sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
            sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
            success: function (res) {
              const localIds = res.localIds // 返回选定照片的本地ID列表，localId可以作为img标签的src属性显示图片
              console.log(localIds)
              if(localIds.length>0){
                self.wxUploadPic(localIds, id, index, eqId)
              }
            }
          })
        }
      })
    },
    wxUploadPic(localIds, id, index, eqId){
      const self = this
      this.checkJsApi("scanQRCode").then((rel) => {
        if (rel) {
          wx.getLocalImgData({
            localId: localIds[0].toString(),
            success: function (res) {
              const localData = res.localData
              let imageBase64 = ''
              if (localData.indexOf('data:image') == 0) {
                //苹果的直接赋值，默认生成'data:image/jpeg;base64,'的头部拼接
                imageBase64 = localData
              } else {
                //此处是安卓中的唯一得坑！在拼接前需要对localData进行换行符的全局替换
                //此时一个正常的base64图片路径就完美生成赋值到img的src中了
                imageBase64 = 'data:image/jpeg;base64,' + localData.replace(/\n/g, '')
              }
              if (imageBase64) {
                let param = {
                  base64data: imageBase64,
                  id
                }
                console.log('image',param)
                console.log(self.showSize(imageBase64))
                API.photo(param).then(res => {
                  // self.eqList[index].v.photo = res
                  // console.log(self.eqList[eqId][index].v.photo = res)
                  self.eqList[eqId][index].v.photo = res.data.img_path
                  console.log(index)
                  console.log(res)
                  // self.index()
                })
              } else {
                Toast("选择图片出了点问题，请稍后再试下吧");
              }
            }
          })
        }
      })
    },
    handOut() {
      const id = this.data.id
      API.giveOut(id).then((response) => {
        if (response.data.error_code === 1) {
          Notify({
            message: '恭喜你，派发成功',
            type: 'success'
          })
          this.goUrl('/order/pm3')
        } else {
          Notify({
            type: 'danger',
            message: response.data.message
          })
        }
      })
    },
    appendAdminHandle() {
      const that = this
      if (!this.adminId) {
        Notify({
          type: 'danger',
          message: '请先选择人员'
        })
        return false
      }
      const admin_data = {
        'admin_id': this.adminId,
        'work_order_id': this.$route.params.id
      }
      API.appendMember(admin_data).then(response => {
        if (response.data.error_code === 1) {
          Notify({
            message: '恭喜你，新增成功',
            type: 'success'
          })
          API.getOne(this.$route.params.id).then(res => {
            that.data = res.data
          })
          this.adminId = null
          this.adminPicker = null
        } else {
          Notify({
            type: 'danger',
            message: '该人员已存在'
          })
        }
      })
    },
    onConfirm(a) {
      this.adminPicker = a.name
      this.adminId = a.id
      this.showAdminPicker = false
    },
    searchPicker() {
      this.loadingPicker = true
      SELECT.adminList(this.adminQuery).then(res => {
        this.adminList = res.data.data
      }).finally(() => {
        this.loadingPicker = false
      })
    },
    removeAdmin(id) {
      const that = this
      API.removeMember({id}).then((response) => {
        if (response.data.error_code === 1) {
          Notify({
            type: 'success',
            message: '恭喜你，删除成功'
          })
          API.getOne(this.$route.params.id).then(res => {
            that.data = res.data
          })
        } else {
          Notify({
            type: 'danger',
            message: response.data.message
          })
        }
      })
    },
    onPartsConfirm(p) {
      this.partsNumber = p.number + p.invisible_number
      this.showPartsPicker = false
      this.partsPicker = p.name
      this.partsId = p.id
    },
    searchPartsPicker(){
      this.loadingPicker = true
      // this.partsQuery
      SELECT.partsList(this.partsQuery).then(partsRes => {
        this.partsList = partsRes.data.data
      }).finally(() => {
        this.loadingPicker = false
      })
    },
    appendPartsHandle() {
      const self = this
      if (!this.partsId) {
        Notify({
          type: 'danger',
          message: '请先选择所需的备件'
        })
        return false
      }
      if (Number(this.needPartsNumber) === 0) {
        Notify({
          type: 'danger',
          message: '数量格式不正确'
        })
        return false
      }
      if (this.needPartsNumber > this.partsNumber) {
        Notify({
          type: 'danger',
          message: '需要数量过多，请先请求部分！'
        })
        return false
      }
      const parts_data = {
        'parts_id': this.partsId,
        'notice': null,
        'number': this.needPartsNumber,
        'work_order_id': this.$route.params.id
      }
      API.appendParts(parts_data).then(response => {
        if (response.data.error_code === 1) {
          Notify({
            type: 'success',
            message: '恭喜你，新增成功'
          })
          self.index()
          self.partsId = null
          self.needPartsNumber = null
          self.partsNumber = null
        } else {
          Notify({
            type: 'danger',
            message: response.data.message
          })
        }
      })
    },
    removePartsHandle(id, already) {
      const self = this
      if (already === 2) {
        Notify({
          type: 'danger',
          message: '已经领取到手了，不能直接删除'
        })
        return false
      }
      const parts_data = {
        'id': id
      }
      API.removeParts(parts_data).then((response) => {
        if (response.data.error_code === 1) {
          Notify({
            type: 'success',
            message: '恭喜你，删除成功'
          })
          self.index()
        } else {
          Notify({
            type: 'danger',
            message: response.data.message
          })
        }
      })
    },
    searchEq() {
      const that = this
      this.checkJsApi("scanQRCode").then((rel) => {
        if (rel) {
          wx.scanQRCode({
            needResult: 1, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
            scanType: ["qrCode", "barCode"], // 可以指定扫二维码还是一维码，默认二者都有
            success: function (res) {
              const code = res.resultStr
              const kinds = code.split('|')
              if (kinds.length !== 2) {
                alert('此二维码格式不对，请联系管理员！！')
              }
              if (kinds[0] === 'e') {
                // 设备
                SELECT.eqList({coding: kinds[1]}).then(eqRes => {
                  if (eqRes.data.error_code) {
                    Notify({
                      type: 'danger',
                      message: eqRes.data.message
                    })
                  } else {
                    const eq = eqRes.data.data[0]
                    that.activeName = eq.id+'1'

                    //查询当前工单对应的当台设备
                    const eqId = eq.id
                    const workorderId = that.$route.params.id
                    API.SelectEqTime({
                      'equipment_id': eqId,
                      'workorder_id': workorderId
                    }).then(res => {
                      console.log(res)
                    })
                  }
                })
              } else {
                alert('这不是设备的二维码')
              }
            }
          })
        }
      })
    },
    appendDelay() {
      const self = this
      const day = self.delayData.day
      const reason = self.delayData.day
      if (!day || !reason) {
        Notify({
          type: 'danger',
          message: '请填写天数和原因！'
        })
      } else {
        const data = {
          'day': day,
          'reason': reason,
          'admin_id': self.userId,
          'work_order_id': self.$route.params.id
        }
        API.appendDelay(data).then(response => {
          if (response.data.error_code === 1) {
            Notify({
              type: 'success',
              message: '请求延期成功'
            })
            API.getOne(self.$route.params.id).then(response => {
              self.delayList = response.data.delays
            })
          } else {
            Notify({
              type: 'danger',
              message: response.data.message
            })
          }
        })
      }
    },
    reviewDelay(id, status) {
      const self = this
      const reviewData = {
        'status': status,
        'id': id,
        'workorder_id': this.$route.params.id
      }
      API.reviewDelay(reviewData).then((response) => {
        if (response.data.error_code === 1) {
          Notify({
            type: 'success',
            message: '审核成功！'
          })
          self.index()
        } else {
          Notify({
            type: 'danger',
            message: response.data.message
          })
        }
      })
    },
  }
}
</script>

<style scoped>
.order-detail{
  box-sizing: border-box;
  text-align: left;
  padding: 10px 10px 80px;
}
.order-detail .innerBox{
  border-bottom: 1px dashed #999;
  margin-bottom: 10px;
}
.order-detail .innerBox .innerReading{
  margin-bottom: 10px;
}
.van-field__control{
  border: 1px solid !important;
  padding-left: 10px;
}
.mb20{
  margin-bottom: 20px;
}
.mr10{
  margin-right: 10px;
}
.font-black{
  color: #000000;
}
</style>
